<?php
// $Id$

/**
 * Smslog 封装来自 sms_log 数据表的记录及领域逻辑
 */
class paper extends QDB_ActiveRecord_Abstract
{

    /**
     * 返回对象的定义
     *
     * @static
     *
     * @return array
     */
    static function __define()
    {
        return array
        (
            // 指定该 ActiveRecord 要使用的行为插件
            'behaviors' => '',

            // 指定行为插件的配置
            'behaviors_settings' => array
            (
                # '插件名' => array('选项' => 设置),
            ),

            // 用什么数据表保存对象
            'table_name' => 'edu_paper_paper',

            // 指定数据表记录字段与对象属性之间的映射关系
            // 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
            'props' => array
            (
                // 主键应该是只读，确保领域对象的“不变量”
                'id' => array('readonly' => true),

                // 对象创建时间应该是只读
                'created' => array('readonly' => true),


                /**
                 *  可以在此添加其他属性的设置
                 */
                # 'other_prop' => array('readonly' => true),

                /**
                 * 添加对象间的关联
                 */
                # 'other' => array('has_one' => 'Class'),
//         	'agent'=>array('has_one'=>'acct','source_key'=>'agent_id','target_id'=>'id'),
//             'admin'=>array('has_one'=>'acct','source_key'=>'admin_id','target_id'=>'id')

            ),

            /**
             * 允许使用 mass-assignment 方式赋值的属性
             *
             * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
             */
            'attr_accessible' => '',

            /**
             * 拒绝使用 mass-assignment 方式赋值的属性
             */
            'attr_protected' => 'id',

            /**
             * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
             *
             * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
             */
            'create_reject' => '',

            /**
             * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
             */
            'update_reject' => '',

            /**
             * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
             *
             * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
             * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
             *
             * 如果填充值为一个数组，则假定为 callback 方法。
             */
            'create_autofill' => array
            (
                # 属性名 => 填充值
                # 'is_locked' => 0,

                'created' => self::AUTOFILL_TIMESTAMP ,
            ),

            /**
             * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
             *
             * 填充值的指定规则同 create_autofill
             */
            'update_autofill' => array
            (
            ),

            /**
             * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
             *
             * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
             *
             * 如果需要添加一个自定义验证，应该写成
             *
             * 'title' => array(
             *        array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
             * )
             *
             * 然后在该类中添加 checkTitle() 方法。函数原型如下：
             *
             * static function checkTitle($title)
             *
             * 该方法返回 true 表示通过验证。
             */
            'validations' => array
            (

            ),
        );
    }


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

    /**
     * 开启一个查询，查找符合条件的对象或对象集合
     *
     * @static
     *
     * @return QDB_Select
     */
    static function find()
    {
        $args = func_get_args();
        return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
    }

    /**
     * 返回当前 ActiveRecord 类的元数据对象
     *
     * @static
     *
     * @return QDB_ActiveRecord_Meta
     */
    static function meta()
    {
        return QDB_ActiveRecord_Meta::instance(__CLASS__);
    }


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
    //题库首页信息
    static function getindexinfo($user_id){
        //做题数量
        $now_day = strtotime(date("Y-m-d",time()));
        $dolog_num = paperquestiondolog::find(['user_id'=>$user_id,'is_do'=>1])->getCount('id');
        $today_dolog_num = paperquestiondolog::find("user_id=$user_id and is_do=1 and created>$now_day")->getCount('id');
        //平均正确率
        $sql = "SELECT
                avg( right_per ) as c 
            FROM
                edu_paper_exam 
            WHERE
                user_id = $user_id ";
        $right_per = QDB::getConn()->execute($sql)->fetchAll();
        $avg_right_per = empty($right_per[0]['c'])?0:$right_per[0]['c'];
        //今日正确率
        $sql = "SELECT
                avg( right_per ) as c 
            FROM
                edu_paper_exam 
            WHERE
                user_id = $user_id 
                and created>$now_day";
        $today_right_per = QDB::getConn()->execute($sql)->fetchAll();
        $today_avg_right_per = empty($today_right_per[0]['c'])?0:$today_right_per[0]['c'];

        $sql = "SELECT
                COUNT( DISTINCT user_id ) as c 
            FROM
                edu_paper_exam ";
        $join_num = QDB::getConn()->execute($sql)->fetchAll();
        $join_num = empty($join_num[0]['c'])?0:$join_num[0]['c'];

        $sql = "SELECT
                COUNT( DISTINCT day_time ) as c 
            FROM
                edu_paper_exam 
            WHERE
                user_id = $user_id";
        $do_day = QDB::getConn()->execute($sql)->fetchAll();
        $do_day = empty($do_day[0]['c'])?0:$do_day[0]['c'];

        // $join_num = paperexam::find()->group("user_id")->getCount();
        // $do_day = paperexam::find("user_id=?",$user_id)->group("day_time")->getCount();
        $data = array(
            "dolog_num"=>$dolog_num?$dolog_num:0,
            "today_dolog_num"=>$today_dolog_num?$today_dolog_num:0,
            "avg_right_per"=>round($avg_right_per,2),
            "today_avg_right_per"=>round($today_avg_right_per,2),
            "join_num"=>$join_num?$join_num:0,
            "do_day"=>$do_day?$do_day:0
        );
        return $data;
    }

    //获取paper信息
    static function getpaperinfo($paper_id,$user_id){
        $paper = paper::find("id = ".$paper_id)->getOne();
        if($paper->id()){
            $paper_info = $paper->toArray();
        }else{
            $paper = new self();
            return $paper->toArray();
        }
        $paper_info['timelong'] = intval($paper_info['timelong'])*60;//换算成s

        //收藏信息
        // $paper_info['is_collect'] = papersubjectcollection::getcollectstatus($paper_id,$user_id);
        //判断是否做过
        $exam = paperexam::find(array("paper_id"=>$paper_id,"user_id"=>$user_id))->getOne();
        $paper_info['dolog'] = $exam->id()?1:0;
        return $paper_info;
    }
    //获取paper类型 type--0：普通章节1：试卷id
    static function getpapertype($paper_id){
        $host = Helper_Common::getRequestHost();
       			$filename = Q::ini('app_config/ROOT_DIR').'/config/redis.yaml';
			$config = Helper_YAML::load($filename);
			$redis = new Redis();
			$redis->pconnect($config['host'],$config['port']);
        if($redis->exists("edulive:$host:paper_type:".$paper_id)){
            return $redis->get("edulive:$host:paper_type:".$paper_id);
        }
        $paper_info = paper::find("id = ".$paper_id)->setColumns('chapter_id,generalcourse_id')->getOne();
        if($paper_info->chapter_id>0){
            $redis->set("edulive:$host:paper_type:".$paper_id,0);
            $redis->expire("edulive:$host:paper_type:".$paper_id,86400);
            return 0;
        }elseif($paper_info->generalcourse_id>0){
            $redis->set("edulive:$host:paper_type:".$paper_id,1);
            $redis->expire("edulive:$host:paper_type:".$paper_id,86400);
            return 1;
        }
    }
    //试卷列表type--0：普通章节1：试卷id
    static function getlist($id,$type=1){
        $res =array();
        if($type==0){

            $res = paper::find(array("chapter_id"=>$id,'status'=>1))->asArray()->getAll();
        }elseif($type==1){
            $res = paper::find(array("generalcourse_id"=>$id,'status'=>1))->asArray()->getAll();
        }
        return $res;
    }

    //根据paper获取上级科目信息
    static function getsubjectinfo($paper_id){
        if(empty($paper_id)){
            return false;
        }
        $host = Helper_Common::getRequestHost();
        $filename = Q::ini('app_config/ROOT_DIR').'/config/redis.yaml';
        $config = Helper_YAML::load($filename);
        $redis = new Redis();
        $redis->pconnect($config['host'],$config['port']);
        $rv = $redis->get("edulive:$host:paper_info:".$paper_id);
        if(!empty($rv)){
            return json_decode($redis->get("edulive:$host:paper_info:".$paper_id),true);
        }else{
            $paper_info = paper::find("id = ".$paper_id)->getOne();
            $data['paper_id']=$paper_id;
            if($paper_info->generalcourse_id>0){
                $data['type']=1;
                $generalcourse = papergeneralcourse::find("id = ".$paper_info->generalcourse_id)->getOne();
                $data['generalcourse_id']=$paper_info->generalcourse_id;
                $data['subject_id']=$generalcourse->subject_id;
            }else{
                $data['type']=0;
                $chapter = papercoursechapter::find("id = ".$paper_info->chapter_id)->getOne();
                $course = papercourse::find("id = ".$chapter->course_id)->getOne();
                $data['chapter_id']=$paper_info->chapter_id;
                $data['course_id']=$chapter->course_id;
                $data['subject_id']=$course->subject_id;
            }
            $redis->set("edulive:$host:paper_info:".$paper_id,json_encode($data));
            $redis->expire("edulive:$host:paper_info:".$paper_id,86400);
            $redis->close();
            return $data;
        }
    }

    //检查用户试卷vip权限
    static function checkUserAuth($paper_id,$user_id){
        $subject = paper::getsubjectinfo($paper_id);
        //判断是否分享
        $paper = self::find("id=?",$paper_id)->getOne();
        if($paper->id()){
            if($paper->type==1){
                return true;
            }
            //分享
            elseif($paper->type==2){
                $is_share = papershare::checkShare($paper_id,$user_id);
                if($is_share){
                    return true;
                }
            }
            //支付
            elseif($paper->type==3){
                $is_pay = paperorder::checkPay($paper_id,$user_id);
                if($is_pay){
                    return true;
                }
            }
        }
        //综合题
        if(!empty($subject['generalcourse_id'])){
            $gen = papergeneralcourse::find("id = ".$subject['generalcourse_id'])->getOne();
            if($gen->viplevel==0){
                return true;
            }else{
                //用户vip等级
                $viplevel = Acctuser::getuserviplevel($user_id);
                if($viplevel>0 && in_array($viplevel, explode(",", $gen->viplevel))){
                    return true;
                }else{
                    return false;
                }
            }
        }
        if(!empty($subject['course_id'])){
            $course = papercourse::find("id = ".$subject['course_id'])->getOne();
            // if($course->viplevel==0){
            //     return true;
            // }else{
                //用户vip等级
                $viplevel = Acctuser::getuserviplevel($user_id);
                if($viplevel>0 && in_array($viplevel, explode(",", $course->viplevel))){
                    return true;
                }else{
                    return false;
                }
            // }
        }
    }
    /**
     * 搜索
     * @Author   xy
     * @DateTime 2020-02-18T12:15:44+0800
     * @param    string                   $keyword [description]
     * @return   [type]                            [description]
     */
    static function search($keyword=''){
        if($keyword){
            $res = self::find("status=1 and title like '%".$keyword."%' ")->asArray()->getAll();

        }else{
            $res = self::find('status=1')->asArray()->getAll();
        }
        return $res;
    }

    static function getpapername($id){
        $res = self::find('id=?',$id)->getOne();
        if($res->id()){
            return $res->title;
        }
        return '';
    }
}

